<?php

/**
 * Created by PhpStorm.
 * User: yf
 * Date: 2018/3/3
 * Time: 下午6:47
 */
namespace App\Model;

use App\Server\PoolServer\MysqlPool2;
use EasySwoole\Core\Component\Di;
use EasySwoole\Core\Swoole\Coroutine\Client\Mysql;
//use EasySwoole\Core\Swoole\Coroutine\PoolManager;
use EasySwoole\Core\Component\Pool\PoolManager;
use App\Utility\BaseException;
use Exception;
 
class Model
{

    public $prefix = "chat_";

    private $db;

    private $pool;

    private $isfiee = true;

    function __construct()
    {}

    function getModel()
    {
        try {
            $pool = PoolManager::getInstance()->getPool(MysqlPool2::class);
            $this->pool = $pool;
            
            if (empty($pool)) {
                $this->isfiee = false;
                throw new BaseException([
                    "code" => 000010,
                    "msg" => "Model pool 异常"
                ]);
            }
            $obj = $pool->getObj();
            if (empty($obj)) {
                $this->isfiee = false;
                throw new BaseException([
                    "code" => 000011,
                    "msg" => "Model obj 获取失败"
                ]);
            }
            $this->db = $this->pool->getObj();
        } catch (Exception $e) {
            $this->db = Di::getInstance()->get('MYSQL');
        }
    }

    function dbConnector()
    {
        return $this->db;
    }

    function free()
    {
        if ($this->isfiee) {
            if (! empty($this->db)) {
                $this->pool->freeObj($this->db);
            }
        }
    }

    function getLastError()
    {
        return $this->db->getLastError();
    }

    function getLastErrno()
    {
        return $this->db->getLastErrno();
    }

    function getLastQuery()
    {
        return $this->db->getLastQuery();
    }
}